<?php
/**
 * Created by PhpStorm.
 * User: ylq
 * Date: 2018/8/10
 * Time: 11:45
 */

namespace app\api\core\wechat;

use app\api\core\CreateUuid;
use \Cm;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use yii\helpers\VarDumper;

class wxAnalysis extends wechat
{
    /**
     * 基础api
     */
    const API_URL_PREFIX = 'https://api.weixin.qq.com/datacube/';

    //用户统计
    #1、获取用户增减数据
    const USER_SUMMARY_URl = 'getusersummary?access_token=';
    #1、获取累计用户数据
    const USER_CUMULATE_URl = 'getusercumulate?access_token=';

    //消息统计
    const MSG_STREAM_URL = 'getupstreammsg?access_token=';

    //获取图文统计数据:总数据
    const ARTICLE_READ_URL = 'getuserread?access_token=';

    const ARTICLE_SHARE_URL = 'getusershare?access_token=';#//获取图文分享转发数据
    const ARTICLE_READ_EVERYDAY_URL = 'getarticletotal?access_token=';#//获取图文群发总数据（getarticletotal）

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取用户分析的统计数据
     */
    public function analysisUser($appid,  $begin_date='', $end_date='', $total = true)
    {
        if (!$this->getAuthInfo($appid)) {
            return false;
        }

        $authorizer_access_token = $this->getAuthorizerAccessToken($appid);
        if (!$authorizer_access_token) {
            return false;
        }
        $date = [];
        $countData = [];
        //时间区间
       if (!empty($end_date) && !empty($end_date)) {
            $date = [
                [
                    'begin_date'=>$begin_date,
                    'end_date'=>$end_date,
                ]
            ];
            $countData = $date;
        } else {
            //当前一个月
            $start = date('Y-m-01');
            $end = date('Y-m-d');
            $suff = strtotime($end)-strtotime($start);
            $k = ceil($suff/(7*24*3600));

            for ($i=1; $i <= $k; $i++) {
                $tem_start = ($i-1) * 7 + 1;
                $tem_end = $tem_start+6;
                if ((int)$tem_end >= (int)date('d')) {
                    $tem_end = date('d')-1;
                } else {
                    $tem_end =   (int)$tem_end >= 10 ? $tem_end : '0'.$tem_end;
                }
                $date[$i-1] = [
                    'begin_date'=>date('Y-m-').((int)$tem_start >= 10 ? $tem_start : '0'.$tem_start),
                    'end_date'=>date('Y-m-').$tem_end,
                ];
            }

            //计算获取总数
            $countData = $date;
        }


        if (is_array($countData) && !empty($countData)) {
            foreach ($countData as $v) {
                $data = json_encode($v);
                //这里最后一天的数据有话 不需要更新：重点
                $update = Cm::$db->one("select count_status from `scrm_weixin_user_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `date`='{$v['end_date']}'");
                if ($update && (int)$update['count_status']===1) {
                    continue;
                }
                $result = $this->http_post(self::API_URL_PREFIX.self::USER_CUMULATE_URl.$authorizer_access_token,$data);


                $jsonArray = json_decode($result,true);

                if (isset($jsonArray['errcode'])) {
                    $this->errCode = $jsonArray['errcode'];
                    $this->errMsg = $jsonArray['errmsg'];
                    $this->error = $jsonArray['errmsg'];
                }
                if (isset($jsonArray['list'])) {
                    $json = $jsonArray['list'];

                    if (is_array($json) && !empty($json)) {
                        foreach ($json as $item) {
                            $data = [
                                'wx_account_id'=>$this->wx_app_data_id,
                                'cumulate_user'=>(int)$item['cumulate_user'],
                                'user_source'=>(int)$item['user_source'],
                                'count_status'=>1,
                            ];


                            $resultData = Cm::$db->one("select id from `scrm_weixin_user_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `date`='{$item['ref_date']}'");

                            if (!$resultData) {
                                $data['date'] = $item['ref_date'];
                                $data['id']=(new \app\api\core\CreateUuid())->toString();
                                Cm::$db->insert('scrm_weixin_user_count', $data);
                            } else {
                                Cm::$db->update('scrm_weixin_user_count', $data, "wx_account_id='{$this->wx_app_data_id}' and `date`='{$item['ref_date']}'");
                            }
                        }
                    }
                }




            }
        }

        //计算其他的关注用户数，净增用户数等
        if (is_array($date) && !empty($date)) {
            foreach ($date as $item) {
                $data = json_encode($item);
                //这里最后一天的数据有话 不需要更新：重点

                $update = Cm::$db->one("select add_status from `scrm_weixin_user_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `date`='{$item['end_date']}'");
                if ($update && (int)$update['add_status']===1) {
                    continue;
                }

                $result = $this->http_post(self::API_URL_PREFIX.self::USER_SUMMARY_URl.$authorizer_access_token,$data);

                if ($result) {
                    $jsonArray = json_decode($result,true);
                    if (isset($jsonArray['errcode'])) {
                        $this->errCode = $jsonArray['errcode'];
                        $this->errMsg = $jsonArray['errmsg'];
                        $this->error = $jsonArray['errmsg'];
                    }

                    if (isset($jsonArray['list'])) {
                        $json = $jsonArray['list'];
                        if (is_array($json) && !empty($json)) {
                            foreach ($json as $row) {
                                $data = [
                                    'wx_account_id'=>$this->wx_app_data_id,
                                    'user_source'=>(int)$row['user_source'],
                                    'new_user'=>(int)$row['new_user'],
                                    'cancel_user'=>(int)$row['cancel_user'],
                                    'add_status'=>1,
                                    //净增用户数量:new_user减去cancel_user
                                    'clean_user'=>(int)$row['new_user']-(int)$row['cancel_user'],
                                ];
                                $resultData = Cm::$db->one("select id from `scrm_weixin_user_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `date`='{$row['ref_date']}'");
                                if (!$resultData) {
                                    $data['date'] = $row['ref_date'];
                                    $data['id']=(new \app\api\core\CreateUuid())->toString();
                                    Cm::$db->insert('scrm_weixin_user_count', $data);
                                } else {
                                    Cm::$db->update('scrm_weixin_user_count', $data, "wx_account_id='{$this->wx_app_data_id}' and `date`='{$row['ref_date']}'");
                                }
                            }


                        }
                    }

                }

            }
        }

        return true;
    }

    /**
     * 获取消息发布统计数据：
     * @param $appid
     * @param string $begin_date
     * @param string $end_date
     * @param bool $total
     */
    public function analysisMsg($appid,  $begin_date='', $end_date='', $total = true)
    {
        if (!$this->getAuthInfo($appid)) {
            return false;
        }

        $authorizer_access_token = $this->getAuthorizerAccessToken($appid);
        if (!$authorizer_access_token) {
            return false;
        }
        $date = [];
        $countData = [];
        //时间区间
        $start  = false;
        if (!empty($end_date) && !empty($end_date)) {
            $date = [
                [
                    'begin_date'=>$begin_date,
                    'end_date'=>$end_date,
                ]
            ];
            $start = true;
        } else {
            $start = date('Y-m-01');
            $end = date('Y-m-d');
            $suff = strtotime($end)-strtotime($start);
            $k = ceil($suff/(7*24*3600));

            for ($i=1; $i <= $k; $i++) {
                $tem_start = ($i-1) * 7 + 1;
                $tem_end = $tem_start+6;
                if ((int)$tem_end >= (int)date('d')) {
                    $tem_end = date('d')-1;
                } else {
                    $tem_end =   (int)$tem_end >= 10 ? $tem_end : '0'.$tem_end;
                }
                $date[$i-1] = [
                    'begin_date'=>date('Y-m-').((int)$tem_start >= 10 ? $tem_start : '0'.$tem_start),
                    'end_date'=>date('Y-m-').$tem_end,
                ];
            }
        }

        foreach ($date as $item) {
            //开始计算日期：
            $update = Cm::$db->one("select `date` from `scrm_weixin_message_count` WHERE  wx_account_id='{$this->wx_app_data_id}' and `date`='{$item['end_date']}'");
            if ($update ) {
                continue;
            }

            $data = self::json_encode($item);
            $result = $this->http_post(self::API_URL_PREFIX.self::MSG_STREAM_URL.$authorizer_access_token,$data);

            $jsonArray = json_decode($result,true);

            if (isset($jsonArray['errcode'])) {
                $this->errCode = $jsonArray['errcode'];
                $this->errMsg = $jsonArray['errmsg'];
                $this->error = $jsonArray['errmsg'];
            }
            if (isset($jsonArray['list']) && !empty($jsonArray['list'])) {
                $json = $jsonArray['list'];
                if (is_array($json) && !empty($json)) {
                    foreach ($json as $item) {
                        $data = [
                            'wx_account_id'=>$this->wx_app_data_id,
                            'msg_type'=>(int)$item['msg_type'],
                            'msg_user'=>(int)$item['msg_user'],
                            'msg_count'=>(int)$item['msg_count'],
                            //'user_source'=>(int)$item['user_source'],
                        ];

                        $resultData = Cm::$db->one("select id from `scrm_weixin_message_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `date`='{$item['ref_date']}'");
                        if (!$resultData) {
                            $data['date'] = $item['ref_date'];
                            $data['id'] = (new CreateUuid())->toString();
                            Cm::$db->insert('scrm_weixin_message_count', $data);
                        } else {
                            Cm::$db->update('scrm_weixin_message_count', $data, "wx_account_id='{$this->wx_app_data_id}' and `date`='{$item['ref_date']}'");
                        }
                    }
                }
            }
        }


        return true;
    }

    /**
     * 统计图文分析数据报告：
     * 获取图文统计数据（getuserread）
     * 获取图文分享转发数据（getusershare）
     * 获取图文群发总数据（getarticletotal）
     * @param $appid
     * @param string $begin_date
     * @param string $end_date
     * @param bool $total
     * @return bool
     */
    public function analysisArticle($appid,  $begin_date='', $end_date='', $total = true)
    {
        $this->analysisArticleTotal($appid, $begin_date, $end_date, $total);
        $this->analysisArticleShare($appid, $begin_date, $end_date, $total);
        $this->analysisArtcleEveryDayCount($appid, $begin_date, $end_date, $total);
        return true;
    }
    /**
     * 统计图文文章阅读数据
     */
    public function analysisArticleTotal($appid,  $begin_date='', $end_date='', $total = true)
    {
        //获取图文统计数据（getuserread）

        if (!$this->getAuthInfo($appid)) {
            return false;
        }

        $authorizer_access_token = $this->getAuthorizerAccessToken($appid);
        if (!$authorizer_access_token) {
            return false;
        }

        if (!empty($end_date) && !empty($end_date)) {
            $date = [
                [
                    'begin_date'=>$begin_date,
                    'end_date'=>$end_date,
                ]
            ];
            $start = true;
        } else {
            $start = date('Y-m-01');
            $end = date('Y-m-d');
            $suff = strtotime($end)-strtotime($start);
            $k = ceil($suff/(3*24*3600));

            for ($i=1; $i <= $k; $i++) {
                $tem_start = ($i-1) * 3 + 1;
                $tem_end = $tem_start+2;
                if ((int)$tem_end >= (int)date('d')) {
                    $tem_end = date('d')-1;
                } else {
                    $tem_end =   (int)$tem_end >= 10 ? $tem_end : '0'.$tem_end;
                }
                $date[$i-1] = [
                    'begin_date'=>date('Y-m-').((int)$tem_start >= 10 ? $tem_start : '0'.$tem_start),
                    'end_date'=>date('Y-m-').$tem_end,
                ];
            }
        }

        foreach ($date as $item) {
            $dateJson = self::json_encode($item);

            $update = Cm::$db->one("select `read_status` from `scrm_weixin_article_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `stat_date`='{$item['end_date']}'");
            if ($update && (int)$update['read_status']===1) {
                continue;
            }
            $result = $this->http_post(self::API_URL_PREFIX.self::ARTICLE_READ_URL.$authorizer_access_token, $dateJson);
            if ($result) {
                $jsonArray = json_decode($result,true);
                if (isset($jsonArray['errcode'])) {
                    $this->errCode = $jsonArray['errcode'];
                    $this->errMsg = $jsonArray['errmsg'];
                    $this->error = $jsonArray['errmsg'];
                }

                if (isset($jsonArray['list'])) {
                    $json = $jsonArray['list'];
                    if (!empty($json) && is_array($json)) {
                        foreach ($json as $row) {
                            $data = [
                                'user_source'=>$row['user_source'],
                                'origin_page_read_user'=>$row['ori_page_read_user'],
                                'origin_page_read_count'=>$row['ori_page_read_count'],
                                'share_user'=>$row['share_user'],
                                'share_count'=>$row['share_count'],
                                'add_to_fav_user'=>$row['add_to_fav_user'],
                                'add_to_fav_count'=>$row['add_to_fav_count'],
                                'page_read_user'=>$row['int_page_read_user'],
                                'page_read_count'=>$row['int_page_read_count'],
                                'read_status'=>1,
                            ];

                            $resultData = Cm::$db->one("select id from `scrm_weixin_article_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `stat_date`='{$row['ref_date']}'");
                            if (!$resultData) {
                                $data['stat_date'] = $row['ref_date'];
                                $data['id']=(new \app\api\core\CreateUuid())->toString();
                                $data['wx_account_id']=$this->wx_app_data_id;
                                Cm::$db->insert('scrm_weixin_article_count', $data);
                            } else {
                                Cm::$db->update('scrm_weixin_article_count', $data, "wx_account_id='{$this->wx_app_data_id}' and `stat_date`='{$row['ref_date']}'");
                            }
                        }
                    }
                }
            }
        }

        return true;

    }


    /**
     * 统计图文文章分享总数据
     * @param $appid
     * @param string $begin_date
     * @param string $end_date
     * @param bool $total
     */
    public function analysisArticleShare($appid,  $begin_date='', $end_date='', $total = true)
    {
        if (!$this->getAuthInfo($appid)) {
            return false;
        }

        $authorizer_access_token = $this->getAuthorizerAccessToken($appid);
        if (!$authorizer_access_token) {
            return false;
        }

        if (!empty($end_date) && !empty($end_date)) {
            $date = [
                [
                    'begin_date'=>$begin_date,
                    'end_date'=>$end_date,
                ]
            ];
            $start = true;
        } else {
            $start = date('Y-m-01');
            $end = date('Y-m-d');
            $suff = strtotime($end)-strtotime($start);
            $k = ceil($suff/(3*24*3600));

            for ($i=1; $i <= $k; $i++) {
                $tem_start = ($i-1) * 3 + 1;
                $tem_end = $tem_start+2;
                if ((int)$tem_end >= (int)date('d')) {
                    $tem_end = date('d')-1;
                } else {
                    $tem_end =   (int)$tem_end >= 10 ? $tem_end : '0'.$tem_end;
                }
                $date[$i-1] = [
                    'begin_date'=>date('Y-m-').((int)$tem_start >= 10 ? $tem_start : '0'.$tem_start),
                    'end_date'=>date('Y-m-').$tem_end,
                ];
            }
        }

        foreach ($date as $item) {
            $dateJson = self::json_encode($item);


            $update = Cm::$db->one("select `share_status` from `scrm_weixin_article_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `stat_date`='{$item['end_date']}'");
            if ($update && (int)$update['share_status']===1) {
                continue;
            }

            $result = $this->http_post(self::API_URL_PREFIX.self::ARTICLE_SHARE_URL.$authorizer_access_token, $dateJson);

            if ($result) {
                $jsonArray = json_decode($result,true);
                if (isset($jsonArray['errcode'])) {
                    $this->errCode = $jsonArray['errcode'];
                    $this->errMsg = $jsonArray['errmsg'];
                    $this->error = $jsonArray['errmsg'];
                }

                if (isset($jsonArray['list'])) {
                    $json = $jsonArray['list'];
                    if (!empty($json) && is_array($json)) {
                        foreach ($json as $row) {
                            $data = [
                                //'user_source'=>$row['user_source'],
                                'share_scene'=>$row['share_scene'],
                                'share_user'=>$row['share_user'],
                                'share_count'=>$row['share_count'],
                                'share_status'=>1,
                            ];

                            $resultData = Cm::$db->one("select id from `scrm_weixin_article_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `stat_date`='{$row['ref_date']}'");
                            if (!$resultData) {
                                $data['stat_date'] = $row['ref_date'];
                                $data['id']=(new \app\api\core\CreateUuid())->toString();
                                $data['wx_account_id']=$this->wx_app_data_id;
                                Cm::$db->insert('scrm_weixin_article_count', $data);
                            } else {
                                Cm::$db->update('scrm_weixin_article_count', $data, "wx_account_id='{$this->wx_app_data_id}' and `stat_date`='{$row['ref_date']}'");
                            }
                        }
                    }
                }
            }
        }

        return true;
    }


    public function analysisArtcleEveryDayCount($appid,  $begin_date='', $end_date='', $total = true)
    {


        if (!empty($end_date) && !empty($end_date)) {

            $start = $begin_date;
            $end = $end_date;
            $suff = strtotime($end)-strtotime($start);


            $j = (int)date('d', strtotime($start));
            $k = $j+ceil($suff/(24*3600));

            for ($i=$j; $i <= $k; $i++) {
                $tem_start = ($i-1) * 1 + 1;
                $tem_end = $tem_start+0;
                if ((int)$tem_end >= (int)strtotime($end)) {
                    $tem_end = date('d', strtotime($end))-1;
                } else {
                    $tem_end =   (int)$tem_end >= 10 ? $tem_end : '0'.$tem_end;
                }
                $date[$i-1] = [
                    'begin_date'=>date('Y-m-', strtotime($begin_date)).((int)$tem_start >= 10 ? $tem_start : '0'.$tem_start),
                    'end_date'=>date('Y-m-', strtotime($end_date)).$tem_end,
                ];
            }

        } else {
            $start = date('Y-m-01');
            $end = date('Y-m-d');
            $suff = strtotime($end)-strtotime($start);
            $k = ceil($suff/(1*24*3600));

            for ($i=1; $i <= $k; $i++) {
                $tem_start = ($i-1) * 1 + 1;
                $tem_end = $tem_start+0;
                if ((int)$tem_end >= (int)date('d')) {
                    $tem_end = date('d')-1;
                } else {
                    $tem_end =   (int)$tem_end >= 10 ? $tem_end : '0'.$tem_end;
                }
                $date[$i-1] = [
                    'begin_date'=>date('Y-m-').((int)$tem_start >= 10 ? $tem_start : '0'.$tem_start),
                    'end_date'=>date('Y-m-').$tem_end,
                ];
            }
        }

        if (!$this->getAuthInfo($appid)) {
            return false;
        }

        $authorizer_access_token = $this->getAuthorizerAccessToken($appid);
        if (!$authorizer_access_token) {
            return false;
        }


        foreach ($date as $item) {
            $dateJson = self::json_encode($item);

            $update = Cm::$db->one("select `id` from `scrm_weixin_article_details_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `date`='{$item['end_date']}'");
            if ($update) {
                continue;
            }

            $result = $this->http_post(self::API_URL_PREFIX.self::ARTICLE_READ_EVERYDAY_URL.$authorizer_access_token, $dateJson);

            if ($result) {
                $jsonArray = json_decode($result,true);
                if (isset($jsonArray['errcode'])) {
                    $this->errCode = $jsonArray['errcode'];
                    $this->errMsg = $jsonArray['errmsg'];
                    $this->error = $jsonArray['errmsg'];
                }


                if (isset($jsonArray['list']) && !empty($jsonArray['list'])) {
                    $json = $jsonArray['list'];

                    if (!empty($json) && is_array($json)) {

                        foreach ($json as $item) {
                            if (isset($item['details']) && !empty($item['details']) && is_array($item['details'])) {
                                foreach ($item['details'] as $row) {

                                    $data = [
                                        'title'=>$item['title'],
                                        'user_source'=>$item['user_source'],
                                        'msgid'=>$item['msgid'],
                                        'stat_date'=>$item['ref_date'],
                                        'msgid'=>$item['msgid'],

                                        'target_user'=>$row['target_user'],
                                        //'user_source'=>$row['user_source'],
                                        'origin_page_read_user'=>$row['ori_page_read_user'],
                                        'origin_page_read_count'=>$row['ori_page_read_count'],
                                        'page_read_user'=>$row['int_page_read_user'],
                                        'page_read_count'=>$row['int_page_read_count'],
                                        'share_user'=>$row['share_user'],
                                        'share_count'=>$row['share_count'],
                                        'add_to_fav_user'=>$row['add_to_fav_user'],
                                        'add_to_fav_count'=>$row['add_to_fav_count'],

                                        'int_page_from_session_read_user'=>$row['int_page_from_session_read_user'],
                                        'int_page_from_session_read_count'=>$row['int_page_from_session_read_count'],
                                        'int_page_from_hist_msg_read_user'=>$row['int_page_from_hist_msg_read_user'],
                                        'int_page_from_hist_msg_read_count'=>$row['int_page_from_hist_msg_read_count'],
                                        'int_page_from_feed_read_user'=>$row['int_page_from_feed_read_user'],
                                        'int_page_from_feed_read_count'=>$row['int_page_from_feed_read_count'],
                                        'int_page_from_friends_read_user'=>$row['int_page_from_friends_read_user'],
                                        'int_page_from_friends_read_count'=>$row['int_page_from_friends_read_count'],
                                        'int_page_from_other_read_user'=>$row['int_page_from_other_read_user'],
                                        'int_page_from_other_read_count'=>$row['int_page_from_other_read_count'],
                                        'feed_share_from_session_user'=>$row['feed_share_from_session_user'],
                                        'feed_share_from_session_cnt'=>$row['feed_share_from_session_cnt'],
                                        'feed_share_from_feed_user'=>$row['feed_share_from_feed_user'],
                                        'feed_share_from_feed_cnt'=>$row['feed_share_from_feed_cnt'],
                                        'feed_share_from_other_user'=>$row['feed_share_from_other_user'],
                                        'feed_share_from_other_cnt'=>$row['feed_share_from_other_cnt'],
                                    ];

                                    $imgTemplate = Cm::$db->one("SELECT id from `scrm_weixin_img_template` where msgid='{$data['msgid']}'");
                                    if ($imgTemplate && !empty($imgTemplate['id'])) {
                                        $data['aid'] = $imgTemplate['id'];
                                    }
                                    $resultData = Cm::$db->one("select id from `scrm_weixin_article_details_count` WHERE wx_account_id='{$this->wx_app_data_id}' and `date`='{$row['stat_date']}'");
                                    if (!$resultData) {
                                        $data['date'] = $row['stat_date'];
                                        $data['id']=(new \app\api\core\CreateUuid())->toString();
                                        $data['wx_account_id']=$this->wx_app_data_id;
                                        Cm::$db->insert('scrm_weixin_article_details_count', $data);
                                    } else {
                                        Cm::$db->update('scrm_weixin_article_details_count', $data, "wx_account_id='{$this->wx_app_data_id}' and `date`='{$row['stat_date']}'");
                                    }
                                }
                            }
                        }


                    }
                }
            }
        }
    }
}